package com.example.controller;



import com.example.entity.ResponseEntity;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;


/**
 * 图片验证码控制类
 * @author 李平
 * @Date 2022-5-2
 */
@Controller
public class CaptchaController {

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private static Logger logger = LoggerFactory.getLogger(CaptchaController.class);

    private String img_code = null;

    @RequestMapping("/getImg")
    public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {

        response.setDateHeader("Expires", 0);

        // 设置标准的HTTP/1.1无缓存头信息
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

        // 设置IE扩展的HTTP/1.1无缓存头(使用addHeader)
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");

        // 设置标准HTTP/1.0无缓存报头
        response.setHeader("Pragma", "no-cache");

        // 返回一个jpeg
        response.setContentType("image/jpeg");

        // 为图像创建文本
        String capText = captchaProducer.createText();

        img_code = capText;

        // 用文本创建图像
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();

        // 导出数据
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }

    /**
     * 校验验证码
     * @param httpServletRequest
     * @param code
     * @return ResponseEntity
     */
    @GetMapping("/check-code")
    @ResponseBody
    public ResponseEntity verifyCode(HttpServletRequest httpServletRequest, @RequestParam("code") String code) {
        try{
            if (img_code.equals(code)) {
                return ResponseEntity.ok("验证成功");
            } else {
                return ResponseEntity.err("验证码错误");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            return ResponseEntity.err("验证错误:"+e.getMessage());
        }
    }

}
